<template>
  <div class="searchTop">
     <!-- 头部搜索区 -->
     <div class="searchTopNav">
       <div class="back">
         <i class="iconfont icon-zuojiantou" @click="$router.push('/home')"></i>   
       </div>
       <div class="right"> 
          <input type="text" 
          :placeholder="search.placeholder" 
          @keydown.enter="searchDetail" 
          v-model="search.searchKeyWord"
          ref="input"
          >
       </div>
    </div>
     <!-- 历史记录区域 -->
     <div class="history" >
     <div class="historyLeft">
       历史
     </div>
     <div class="historyRight">
       <div class="keyWordItem" v-for="(item,i) in search.keyWordList" :key="i" @click="historySearch(item)">{{item}}</div>
       <div class="noHistory" v-show="!search.keyWordList.length">暂无搜索记录</div>
     </div>
     <div class="rubbish">
       <i class="iconfont icon-lajitong" @click="cleanRecord"></i>
     </div>
    </div>
    <!-- 搜索匹配区域 -->
    <div class="searchMatch" v-show="search.isShowRecords && search.searchKeyWord!==''">
      <div class="searchMatchList">
        <div class="searchMatchItem" v-for="(item,i) in search.searchMatchs" :key="i" @click="searchMusic(item.name)">
          <i class="iconfont icon-sousuo"></i>
          <div class="content">
           <div class="title">{{item.name}}</div>
          </div>
        </div>
      </div>
    </div>
     <!-- 歌曲显示区域 -->
     <div class="searchSongs" v-show="search.searchSongs.length!=0 && !search.isShowRecords">
    <div class="searchSongs-top">
        <div class="left">
            <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-bofang3"></use>
            </svg>
            <div class="text">
                <div class="title">播放全部</div>
                <div class="num">（共{{search.searchSongs.length}}首）</div>
            </div>
        </div>
    </div>
    <div class="list">
        <div class="playItem" v-for="(item,i) in search.searchSongs" :key="i" @click="playMusicing(item,i)">
            <div class="left">
                <div class="index">{{i+1}}</div>
                <div class="content">
                    <div class="title">{{item.name}}</div>
                    <div class="anthor">
                        <span class="name">{{item.album.name}}</span>
                    </div>
                </div>
            </div>
            <div class="right">
               <i class="iconfont icon-24gl-playSquare"></i>
               <i class="iconfont icon-liebiao"></i>
            </div>
        </div>
    </div>
    </div>
  </div>
</template>

<script>
let timer
import _ from "lodash";
import playCount from '../../utils/playCount.js'
import {searchMusics,getMusicDetail} from '@/api/index.js'
import {mapMutations,useStore} from 'vuex'
import { Dialog } from 'vant';
import {reactive,onBeforeMount,watch,getCurrentInstance,onMounted,toRef,toRefs} from 'vue'
import bus from '@/utils/eventBus.js'
export default {
//vue3写法
 setup(props,context){
  //数据
  const store=useStore()
  let search=reactive({
     placeholder:'陈奕迅',
     keyWordList:[],
     //双向绑定input框获取其中的值
     searchKeyWord:'',
     //搜索后获取的歌曲
     searchSongs:[],
     //搜索匹配列表
     searchMatchs:[],
     //是否展示搜索匹配的框
     isShowRecords:false,
     isSend:false
   })
  
  watch(()=>search.searchKeyWord,function(){
    search.isShowRecords=true
    searchMatchListDetail()
  })

   //方法
   //防抖搜索
   const searchDetail=_.debounce(function(){
     saveKeyWord()
   },1000)
   //节流搜索匹配
   const searchMatchListDetail=_.throttle(function(){
     searchMatchList()
  },400)
   //搜索匹配
   async function searchMatchList(){
    const {data:res}=await searchMusics(search.searchKeyWord)
    console.log(res);
    search.searchMatchs=res.result.songs.slice(0,10)
   }
   //保存搜索记录
   async function saveKeyWord(){
     search.isShowRecords=false
     //没输入时按回车会默认搜索placeholder中的关键词
     if(!search.searchKeyWord){
       search.searchKeyWord=search.placeholder
     }
     search.keyWordList.push(search.searchKeyWord.trim())
     //数组去重，相同记录下只显示一次的记录
     search.keyWordList = Array.from(new Set(search.keyWordList))
     //搜索记录大于10，则取后10个
     if(search.keyWordList.length>10){
      search.keyWordList=search.keyWordList.slice(search.keyWordList.length-10,search.keyWordList.length)
     }
     //将input框中内容存储至本地
     localStorage.keyWordList=JSON.stringify(search.keyWordList)
     //获取音乐
     const {data:res}=await searchMusics(search.searchKeyWord)
     search.searchSongs=res.result.songs
     console.log(res)
     console.log(search.keyWordList);
   }
   //历史记录搜索
   function historySearch(keyword){
     search.searchKeyWord=keyword
     saveKeyWord()
   }
   //播放歌曲
   async function playMusicing(item,i){
     const {data:res}=await getMusicDetail(item.id)
     res.songs[0].al.name=item.name
     let items={
       name: res.songs[0].name,
       id: res.songs[0].id,
       //总时长
       dt:res.songs[0].dt,
       al:res.songs[0].al
     }
     console.log(items);
     store.commit('pushPlaylist',items)
     store.commit('setPlayIndex',store.state.playlist.length-1)
     //点击每个列表时都会直接切换歌曲
     //播放歌曲
     bus.emit('isPlay',false)
     //展示歌曲控件
     store.commit('setShow',true)
     //切歌时把时间更新了
     store.commit('setSumTime',items.duration)
   }
   //搜索记录歌曲
   function searchMusic(name){
     search.isShowRecords=false
     search.searchKeyWord=name
     let timer=setTimeout(()=>{
       saveKeyWord()
     },10)
   }
   //清除搜索记录
   function cleanRecord(){
     Dialog.confirm({
      message: '确定清空全部历史记录？',
    })
      .then(() => {
        search.keyWordList=[]
        window.localStorage.removeItem('keyWordList')
      })
   }
   //生命周期
   onBeforeMount(()=>{
     search.keyWordList=localStorage.keyWordList?JSON.parse(localStorage.keyWordList):[]
   })
   return{
     search,
     saveKeyWord,
     historySearch,
     playMusicing,
     searchMusic,
     cleanRecord,
     searchDetail
     
   }
 }
}
</script>
<style lang="less" scoped>
.searchTop{
  position: relative;
  width: 7.5rem;
  padding:0;
  height:calc(100vh-1.2rem);
  .searchTopNav{
    position: fixed;
    top:0;
    left:0;
    display: flex;
    align-items: center;
    width: 7.5rem;
    height: 1.2rem;
    padding:0 0.4rem;
    background-color: #fff;
    .iconfont{
      font-size: 0.5rem;
    }
    .right{
      padding:0 0 0 0.4rem;
      flex:1;
      input{
        width: 100%;
        border:none;
        outline: none;
        border-bottom: 1px solid #666;
        height: 0.5rem;
      }
    }
  }
  .history{
    position: relative;
    display: flex;
    margin-top:1.2rem;
    align-items: center;
    justify-content:flex-start;
    .historyLeft{
      width: 1rem;
      height: 0.6rem;
      line-height: 0.6rem;
      margin:0.2rem 0;
      text-align: center;
      font-weight: 900; 
    }
    .historyRight{
      position: absolute;
      left:1rem;
      top:0.1rem;
      height: 1.2rem;
      width: 5.5rem;
      // border-right:10px solid #fff;
      // border-right:10px solid rgba(240,240,240,0.5);
      overflow-y:hidden;
      overflow-x:scroll;
      display: flex;
      white-space:nowrap;
      flex-direction: column;
      align-items: center;  
      justify-content:flex-start;
      color: #666;
      flex-wrap: wrap;  
       //隐藏滚动条
      scrollbar-width: none; /* firefox */
      -ms-overflow-style: none; /* IE 10+ */
      .keyWordItem{
        background-color: #eee;
        height: 0.6rem;
        line-height:0.6rem;
        padding:0 0.2rem;
        margin:0.1rem 0.1rem;
        border-radius: 0.2rem;
      }
      .noHistory{
        height: 0.6rem;
        line-height:0.6rem;
        padding:0 0.2rem;
        margin:0.1rem 0.1rem;
      }
    }
    //横向滚动条
    .historyRight::-webkit-scrollbar {
       width: 0 !important/* Chrome Safari */
     }
    .rubbish{
      position: absolute;
      right:0.2rem;
      line-height: 1.2rem;
      .iconfont{
        font-size: 0.45rem;
      }
    }
  }
  .searchMatch{
    position: absolute;
    left:0;
    top:0;
    width: 7.5rem;
    height: 100%; 
    background-color: #fff;
    z-index: 9999;
    .searchMatchItem{
      height: 1rem;
      width: 7.5em;
      padding-left:0.15rem;
      padding-bottom:1rem;
      display: flex;
      align-items: center;
      .iconfont{
      padding:0 0.2rem;
      }
      .title{
        width: 5rem;
      }
    }
  }
  .searchSongs {
    width: 7.5rem;
    padding: 0 0.2rem;
    background-color: #fff;
    border-top-left-radius: 0.3rem;
    border-top-right-radius: 0.3rem;
    margin-top: 0.4rem;
    // padding-bottom:1.5rem;
    position: fixed;
    top:1.6rem;
    bottom:1.2rem;
    overflow: scroll;
    .searchSongs-top {
        display: flex;
        justify-content: space-between;
        height: 1rem;
        align-items: center;

        .left {
            display: flex;
            align-items: center;

            .iconfont {
                font-size:0.6rem
            }

            .title {
                font-size: 0.34rem;
                font-weight: 900;
            }

            .num {
                font-size: 0.24rem;
                color: #666;
            }

            .text {
                display: flex;
                align-items: center;
                margin-left: 0.2rem;
            }

        }

        .btn {
            font-size: 0.24rem;
            color: #fff;
            background-color: orangered;
            line-height: 0.6rem;
            padding: 0.1rem;
            border-radius: 0.4rem;

        }
    }

    .list {
        .playItem {
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 1rem;

            .left {
                flex: 1;
                display: flex;
                align-items: center;
                color: #666;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                word-break: break-all;
                word-wrap: break-word;

                .index {
                    width: 0.4rem;
                    padding-left:0.2rem;
                }

                .content {
                    padding-left: 0.4rem;
                    width: 100%;
                }

                .title {
                    width: calc(100% - 0.4rem);
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    word-break: break-all;
                    word-wrap: break-word;
                    font-size: 0.3rem;
                    font-weight: 900;
                    color: #000;
                    margin-bottom: 0.1rem;
                }

                .tag {
                    font-size: 0.2rem;
                    color: orangered;
                    border: 1px solid orangered;
                    border-radius: 0.1rem;
                    margin-right: 0.1rem;

                }

                .anthor {
                    color: #666;
                    display: flex;
                    overflow: hidden;
                    height: 0.35rem;

                    .name {
                        width: 3rem;
                    }
                }
            }

            .right {
                width: 1.6rem;
                .iconfont {
                    margin: 0 0.2rem
                }
            }

        }
    }
  }
}
</style>